package com.xx.robot.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONObject;
import com.xx.robot.common.util.message.PublicMessageUtil;
import com.xx.robot.common.util.UserUtils;
import com.xx.robot.common.util.gocphttp.CqMessageUtil;
import com.xx.robot.common.util.mongo.MongoDbUtil;
import com.xx.robot.common.bean.CpHttpConfigBean;
import com.xx.robot.common.constant.CollectionNameEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

/**
 * 小本本
 *
 * @author Lenovo
 */
@Slf4j
@Service
public class NiggerRankService {

    private static final Pattern PATTERN = Pattern.compile("\\s*|\t|\r|\n");

    public void blackAndRed(String groupId) {
        String xbb = "红黑榜使用命令：\n" +
                "-----复制格式填写-----\n\n" +
                "黑鬼:某人\n" +
                "原因:工资多少，出玄晶等等\n\n" +
                "欧皇:乌云\n" +
                "原因:工资多少，出玄晶等等\n\n" +
                "---------------------\n" +
                "查询方式：黑鬼榜，欧皇榜，小红手，小黑手\n" +
                "注意哦！请严格安装格式填写，机器人年级还小，做不了太复杂的判断\n" +
                "ps：一旦记录就永远记录榜单了，我才不会删掉呢,默认按照添加时间倒叙\n";
        CqMessageUtil.groupSend(groupId, xbb);
    }

    /**
     * 添加小本本.
     *
     * @param groupId 群id
     * @param message 消息
     * @param user    添加人
     */
    public void addBlackAndRed(String groupId, String message, JSONObject user) {
        // 是否绑定区服
        PublicMessageUtil.isBindServer(groupId);

        if (!UserUtils.isAdminAndManagerAndBot(user)) {
            CqMessageUtil.groupSend(groupId, "你是群主吗？不是。是管理吗？不是。是乌云的小跟班吗？也不是。那下去吧");
            return;
        }

        JSONObject data = new JSONObject();
        if (CharSequenceUtil.startWith(message, "黑鬼")) {
            message = CharSequenceUtil.replace(message, "黑鬼:", CharSequenceUtil.EMPTY);
            data.set("type", "black");
        }
        if (CharSequenceUtil.startWith(message, "欧皇")) {
            message = CharSequenceUtil.replace(message, "欧皇:", CharSequenceUtil.EMPTY);
            data.set("type", "red");
        }
        List<String> messageList = CharSequenceUtil.split(message, "原因:");

        String name = PATTERN.matcher(messageList.get(0)).replaceAll(CharSequenceUtil.EMPTY);
        String reason = PATTERN.matcher(messageList.get(1)).replaceAll(CharSequenceUtil.EMPTY);
        data.set("name", name);
        data.set("reason", reason);

        // 添加人和群相关信息
        data.set("group_id", groupId);
        data.set("add_date", DateUtil.now());
        data.set("add_qq", user.get("user_id").toString());
        data.set("add_nickname", user.getStr("nickname"));

        MongoDbUtil.save(data, "personal_list");
        MongoDbUtil.save(data, CollectionNameEnum.JX3_PERSONAL_RANK.getCode());
        CqMessageUtil.groupSend(groupId, "喵呜！" + CpHttpConfigBean.ROBOT_NAME + "记下了。");
    }

    /**
     * 查询小本本
     *
     * @param groupId 群id
     * @param red     红榜
     */
    public void list(String groupId, boolean red) {
        Query query = new Query();
        Criteria criteria = Criteria.where("group_id").is(groupId);
        if (red) {
            criteria.and("type").is("red");
        } else {
            criteria.and("type").is("black");
        }
        query.with(Sort.by("add_date").descending());

        List<JSONObject> resultList = MongoDbUtil.selectByQuery(query.addCriteria(criteria), JSONObject.class, "personal_list");
        List<JSONObject> resultList2 = MongoDbUtil.selectByQuery(query.addCriteria(criteria), JSONObject.class, CollectionNameEnum.JX3_PERSONAL_RANK.getCode());
        log.info("查询结果：{}", resultList);
        log.info("查询结果：{}", resultList2);

        //组装
        StringBuilder stringBuilder = new StringBuilder();
        if (CollectionUtils.isEmpty(resultList)) {
            CqMessageUtil.groupSend(groupId, "喵呜，这啥都木有呢！");
        }

        stringBuilder.append("榜单：").append("查询最新10条榜单记录额\n");
        stringBuilder.append("------------------------------------------------------\n");

        IntStream.range(0, resultList.size()).forEach(i -> {
            stringBuilder.append(i + 1).append("：")
                    .append(resultList.get(i).get("name"))
                    .append("\t【").append(resultList.get(i).getStr("add_date"))
                    .append("】\n")
                    .append(resultList.get(i).get("reason")).append("\n");
            stringBuilder.append("------------------------------------------------------\n");
        });
        CqMessageUtil.groupSend(groupId, stringBuilder.toString());
    }

    public void xbb(String groupId) {
        String xbb = "小本本使用命令：\n" +
                "-----复制格式填写-----\n\n" +
                "团名:xxx\n" +
                "原因:xxx\n\n" +
                "---------------------\n" +
                "查询方式：小本本+团名\n" +
                "注意哦！一旦记录就永远记录小本本了，我才不会删掉呢\n";
        CqMessageUtil.groupSend(groupId, xbb);
    }


    /**
     * 添加小本本.
     *
     * @param groupId 群id
     * @param message 消息
     * @param user    添加人
     */
    public void addXbb(String groupId, String message, JSONObject user) {

        PublicMessageUtil.isBindServer(groupId);

        message = CharSequenceUtil.replace(message, "团名:", CharSequenceUtil.EMPTY);
        List<String> messageList = CharSequenceUtil.split(message, "原因:");

        JSONObject data = new JSONObject();

        String teamName = PATTERN.matcher(messageList.get(0)).replaceAll(CharSequenceUtil.EMPTY);
        data.set("team_name", teamName);
        String reason = PATTERN.matcher(messageList.get(1)).replaceAll(CharSequenceUtil.EMPTY);
        data.set("reason", reason);

        data.set("group_id", groupId);
        data.set("add_date", DateUtil.today());
        data.set("add_qq", user.getStr("user_id"));
        data.set("add_nickname", user.getStr("nickname"));

        MongoDbUtil.save(data, CollectionNameEnum.JX3_BLACK_LIST_TEAM.getCode());
        String sendMessage = "嗯！" + CpHttpConfigBean.ROBOT_NAME + "记下了\n以后输入命令：\n小本本 " + teamName + "\n就能查询到了哦";
        CqMessageUtil.groupSend(groupId, sendMessage);
    }

    /**
     * 查询小本本
     *
     * @param groupId 群id
     * @param message 团名
     */
    public void findXbb(String groupId, String message) {
        message = message.replaceFirst("小本本", "").trim();

        Query query = Query.query(Criteria.where("group_id").is(groupId).and("team_name").is(message));
        List<JSONObject> resultList = MongoDbUtil.selectByQuery(query, JSONObject.class, CollectionNameEnum.JX3_BLACK_LIST_TEAM.getCode());
        log.info("查询结果：{}", resultList);

        //组装
        StringBuilder stringBuilder = new StringBuilder();
        if (CollectionUtils.isEmpty(resultList)) {
            CqMessageUtil.groupSend(groupId, "这个团还没加入到小本本呢，快去混野吧。");
        }

        stringBuilder.append("团名：").append(message).append("\n");
        stringBuilder.append("查询最新10条小本本记录额\n");
        stringBuilder.append("----------------------------------\n");

        IntStream.range(0, resultList.size()).forEach(i -> {
            stringBuilder.append(i + 1).append("：")
                    .append(resultList.get(i).get("reason"))
                    .append("\t【").append(resultList.get(i).get("add_nickname"))
                    .append("】\n");
            stringBuilder.append("----------------------------------\n");
        });
        CqMessageUtil.groupSend(groupId, stringBuilder.toString());
    }

}
